//JavaScript Framework 2.0 Code
try {
	Type.registerNamespace('com.yonyou.ncmm_pac_pda.PoArriveScanListController');
	com.yonyou.ncmm_pac_pda.PoArriveScanListController = function() {
		com.yonyou.ncmm_pac_pda.PoArriveScanListController.initializeBase(this);
		this.initialize();
	}

	function com$yonyou$ncmm_pac_pda$PoArriveScanListController$initialize() {
		//you can programing by $ctx API
		//get the context data through $ctx.get()
		//set the context data through $ctx.push(json)
		//set the field of the context through $ctx.put(fieldName, fieldValue)
		//get the parameter of the context through $ctx.param(parameterName)
		//Demo Code:
		//    var str = $ctx.getString();      //获取当前Context对应的字符串
		//    alert($ctx.getString())          //alert当前Context对应的字符串
		//    var json = $ctx.getJSONObject(); //获取当前Context，返回值为json
		//    json["x"] = "a";        //为当前json增加字段
		//    json["y"] = [];           //为当前json增加数组
		//    $ctx.push(json);            //设置context，并自动调用数据绑定
		//    
		//    put方法需手动调用databind()
		//    var x = $ctx.get("x");    //获取x字段值
		//    $ctx.put("x", "b");     //设置x字段值
		//    $ctx.put("x", "b");     //设置x字段值
		//    $ctx.databind();            //调用数据绑定才能将修改的字段绑定到控件上
		//    var p1 = $param.getString("p1");   //获取参数p2的值，返回一个字符串
		//    var p2 = $param.getJSONObject("p2");   //获取参数p3的值，返回一个JSON对象
		//    var p3 = $param.getJSONArray("p3");   //获取参数p1的值，返回一个数组

		//your initialize code below...

	}

	function com$yonyou$ncmm_pac_pda$PoArriveScanListController$evaljs(js) {
		eval(js)
	}
	//加载扫描记录
	function com$yonyou$ncmm_pac_pda$PoArriveScanListController$loadScanList(sender, args) {
		// 加载数据的时候判断如果有表则查询，如果不存在数据表则先创建
		NCMMPubUtil.createTable(PoArriveScanVO);
		loadScanListData();

	}

	function com$yonyou$ncmm_pac_pda$PoArriveScanListController$showDetail(sender, args) {
		$view.closePop(popDialogInfo);
		var row = $id("scanlistview").get("row");
		//row = $stringToJSON(row);
		$view.open({
			"viewid": "com.yonyou.ncmm_pac_pda.PoArriveScanDetail", //目标页面（首字母大写）全名
			"isKeep": "true", //打开新页面的同时是否保留当前页面，true为保留，false为不保留
			"row": row
		});
	}

	function com$yonyou$ncmm_pac_pda$PoArriveScanListController$itemDelete(sender, args) {
		$view.closePop(popDialogInfo);
		var params = {
			"title": "提示",
			"message": "确定删除所选记录吗？",
			"okbuttontitle": "确定",
			"cancelbuttontitle": "取消",
			"style": "ok-cancel",
			"okaction": "doDelete()",
			"cancelaction": "doCancel()"
		};
		$view.openDialog(params);
	}

	function doCancel() {
		$toast("删除操作已取消。");
	}

	//执行清除操作
	function doDelete() {
		var row = $id("scanlistview").get("row");
		row = $stringToJSON(row);
		NCMMPubUtil.deleteVO(PoArriveScanVO, row);
		//更新销售订单入库列表增加扫描数量 
		PoArriveUtil.updateScanedNum(row.pk_order_b);
		$toast("删除成功。");
		loadScanListData();
	}

	function getSubScanedNum(scanedNum, currentScanedNum) {
		if(scanedNum == null || scanedNum == "") {
			scanedNum += "00.00000";
		} else {
			scanedNum = parseFloat(scanedNum);
		}
		if(currentScanedNum == null || currentScanedNum == "") {
			currentScanedNum += "1.00000";
		} else {
			currentScanedNum = parseFloat(currentScanedNum);
		}
		var newScanedNum = parseFloat(scanedNum).sub(parseFloat(currentScanedNum));
		return newScanedNum;
	}

	function getQueryRowSql() {
		var sql = "SELECT " +
			PoArriveScanVO.VBILLCODE.name + ", " + PoArriveScanVO.CROWNO.name + ", " +
			PoArriveScanVO.MATERIALNAME.name + ", " + PoArriveScanVO.NSCANNUM.name +
			" FROM " + PoArriveScanVO.prototype.getTableName() +
			" group by " + PoArriveScanVO.VBILLCODE.name + ", " + PoArriveScanVO.CROWNO.name;

		return sql;
	}

	function getScanVOsBySql(data) {
		var rtn = new Array();
		var bitnumberJson = {};
		Array.prototype.map.call(data, function(vo) {
			var vbillcode = vo[PoArriveScanVO.VBILLCODE.name];
			var crowno = vo[PoArriveScanVO.CROWNO.name];
			var wheresql = "where " + PoArriveScanVO.VBILLCODE.name + "='" + vbillcode + "' and " + PoArriveScanVO.CROWNO.name + "='" + crowno + "' ";
			var sum = 0;
			var cunitid = "";
			NCMMPubUtil.queryVO(PoArriveScanVO, wheresql, function(subdata) {
				var showData = eval(subdata);
				showData = NCMMPubUtil.htmlspecialjsonarray2UI(showData);
				if(NCMMPubUtil.isNotEmpty(showData)) {
					for(var i = 0; i < showData.length; i++) {
						var itemData = showData[i];
						if(NCMMPubUtil.isEmpty(bitnumberJson) || NCMMPubUtil.isEmpty(bitnumberJson[itemData["cunitid"]])) {
							var bitnumber = PoArriveUtil.getUnitBitnumber(itemData["cunitid"]);
							if(!NCMMPubUtil.isEmpty(bitnumber)) {
								bitnumberJson[itemData["cunitid"]] = bitnumber;
							}
						}
						if(NCMMPubUtil.isEmpty(bitnumberJson) || NCMMPubUtil.isEmpty(bitnumberJson[itemData["castunitid"]])) {
							var bitnumber = PoArriveUtil.getUnitBitnumber(itemData["castunitid"]);
							if(!NCMMPubUtil.isEmpty(bitnumber)) {
								bitnumberJson[itemData["castunitid"]] = bitnumber;
							}
						}
						if(!NCMMPubUtil.isEmpty(bitnumberJson) && !NCMMPubUtil.isEmpty(bitnumberJson[itemData["cunitid"]])) {

							showData[i]["nnum"] = parseFloat(showData[i]["nnum"]).toFixed(bitnumberJson[itemData["cunitid"]]);
							showData[i]["nscannum"] = parseFloat(showData[i]["nscannum"]).toFixed(bitnumberJson[itemData["cunitid"]]);
						}
						if(!NCMMPubUtil.isEmpty(bitnumberJson) && !NCMMPubUtil.isEmpty(bitnumberJson[itemData["castunitid"]])) {
							showData[i]["nastnum"] = parseFloat(showData[i]["nastnum"]).toFixed(bitnumberJson[itemData["castunitid"]]);
							showData[i]["nscanastnum"] = parseFloat(showData[i]["nscanastnum"]).toFixed(bitnumberJson[itemData["castunitid"]]);
						}

						var scanednum = itemData[PoArriveScanVO.NSCANNUM.name];
						//$alert("sum=" + sum.toString() + " scanednum=" + scanednum);
						sum = PoArriveUtil.getAddNum(sum, scanednum);

					}
					cunitid = showData[0]["cunitid"];
				}
				vo["row"] = showData;
				if(NCMMPubUtil.isEmpty(bitnumberJson) || NCMMPubUtil.isEmpty(bitnumberJson[itemData["castunitid"]])) {
					var bitnumber = PoArriveUtil.getUnitBitnumber(cunitid);
					if(!NCMMPubUtil.isEmpty(bitnumber)) {
						bitnumberJson[cunitid] = bitnumber;
					}
				}
				if(!NCMMPubUtil.isEmpty(bitnumberJson) && !NCMMPubUtil.isEmpty(bitnumberJson[cunitid])) {
					sum = parseFloat(sum).toFixed(bitnumberJson[cunitid]);
				}
				vo["sumScanedNum"] = sum;
				rtn.push(vo);
			});
		});
		return rtn;
	}
	//加载到货单扫描记录
	function loadScanListData() {
		//按照订单号和行号分组查询
		var sql = getQueryRowSql();
		//$alert("sql="+sql);
		var data = NCMMPubUtil.queryBySQL(sql);
		//$alert(data);
		data = eval(data);
		data = NCMMPubUtil.htmlspecialjsonarray2UI(data);
		var scangroups = getScanVOsBySql(data);
		//$alert("scangroups="+$jsonToString({scangroups:scangroups}));
		//显示
		$ctx.push({
			scanlist: scangroups
		});
	}
	//全选
	function com$yonyou$ncmm_pac_pda$PoArriveScanListController$doAllChecked(sender, args) {
		$ctx.dataCollect();
		var isChecked = $id(sender).get("checked");
		var sourceData = $ctx.getJSONArray("scanlist");
		for(var i = 0; i < sourceData.length; i++) {
			sourceData[i]["isChecked"] = isChecked;
			for(var j = 0; j < (sourceData[i]["row"]).length; j++) {
				((sourceData[i]["row"])[j])["ischecked"] = isChecked;
			}
		}

		var json = {};
		json["scanlist"] = sourceData;
		json["isAllChecked"] = isChecked;
		$ctx.push(json); //将数据显示在控件上
	}
	//选中
	function com$yonyou$ncmm_pac_pda$PoArriveScanListController$doChecked(sender, args) {
		var isCheckedAll = true;
		$ctx.dataCollect();
		var sourceData = $ctx.getJSONArray("scanlist");
		for(var i = 0; i < sourceData.length; i++) {
			if(sourceData[i]["isChecked"] == null || sourceData[i]["isChecked"] == false || sourceData[i]["isChecked"] == "false") {
				isCheckedAll = false;
				for(var j = 0; j < (sourceData[i]["row"]).length; j++) {
					((sourceData[i]["row"])[j])["ischecked"] = false;
				}
			} else {
				for(var j = 0; j < (sourceData[i]["row"]).length; j++) {
					((sourceData[i]["row"])[j])["ischecked"] = true;
				}
			}
		}
		$ctx.put("scanlist", sourceData);
		$ctx.put("isAllChecked", isCheckedAll); //更新全选复选框的界面显示
		$ctx.dataBind();
	}
	//提交
	function com$yonyou$ncmm_pac_pda$PoArriveScanListController$doCommit(sender, args) {
		var stordoc = $cache.read("defaultstordoc");
		//if(stordoc == null || stordoc == "") {
		//	$alert("默认仓库不能为空，请设置！");
		//	return;
		//}

		//连接验证成功后的后续处理
		$js.showLoadingBar();
		$ctx.dataCollect();
		var sourceData = $ctx.getJSONArray("scanlist");
		var scanCount = {};
		var scanNum = {};
		var itemPKs = [];
		var headJson = {};
		var itemJson = {};
		var bbitemJson = {};
		var itemKeyJson = {};
		var needCommit = false;
		var hidAndNScanNum = {};
		var headKey = [];
		for(var i = 0; i < sourceData.length; i++) {
			//过滤出需要下载的档案
			if(sourceData[i]["isChecked"] != null && (sourceData[i]["isChecked"] == true || sourceData[i]["isChecked"] == "true")) {
				needCommit = true;

				for(var j = 0; j < sourceData[i]["row"].length; j++) {
					var json = sourceData[i]["row"][j];
					//pk_recvstordoc
					var stordocid;
					if(stordoc == null || stordoc == "") {
						if(NCMMPubUtil.isEmpty(json.pk_recvstordoc)) {
							//$js.hideLoadingBar();
							//$alert("默认仓库不能为空，请设置！");
							//return;
						} else {
							stordocid = json.pk_recvstordoc;
						}
					} else {
						stordocid = $stringToJSON(stordoc).pk_stordoc;
					}
					// if(NCMMPubUtil.isEmpty(stordocid)){				   
					//         $js.hideLoadingBar();			   
					//          $alert("默认仓库不能为空，请设置！");
					//   return;
					// }
					var itemKey = json.pk_order_b + json.vbatchcode;
					itemPKs.push(json.pk_order_b);
					//增加扫描记录数
					if(NCMMPubUtil.isEmpty(scanCount[json.pk_order_b])) {
						scanCount[json.pk_order_b] = 1;
					} else {
						scanCount[json.pk_order_b] = scanCount[json.pk_order_b] + 1;
					}
					//增加扫描累计
					if(NCMMPubUtil.isEmpty(scanNum[json.pk_order_b])) {
						scanNum[json.pk_order_b] = json.nscannum;
					} else {
						scanNum[json.pk_order_b] = getAddScanedNum(scanNum[json.pk_order_b], json.nscannum);
					}
					//处理头map
					if(NCMMPubUtil.isEmpty(headJson) || NCMMPubUtil.isEmpty(headJson[json.pk_order])) {
						var head = {};
						head["pk_order"] = json.pk_order;
						head["ts_h"] = json.hts;
						headJson[json.pk_order] = head;
						headKey.push(json.pk_order);
						itemKeyJson[json.pk_order] = [];
					}
					//处理体Map	
					//处理体Map			
					if(NCMMPubUtil.isEmpty(itemJson) || NCMMPubUtil.isEmpty(itemJson[itemKey])) {
						var item = {};
						item["pk_receivestore"] = stordocid;
						item["pk_order_b"] = json.pk_order_b;
						item["pk_material"] = json.pk_material;
						item["castunitid"] = json.castunitid;
						item["pk_batchcode"] = json.pk_batchcode;
						item["vbatchcode"] = json.vbatchcode;
						item["nscannum"] = json.nscannum;
						item["nscanastnum"] = json.nscanastnum;
						item["bc_vvendbatchcode"] = json.bc_vvendbatchcode;
						itemJson[itemKey] = item;
						var newItemKey = itemKeyJson[json.pk_order];
						newItemKey.push(itemKey);
						itemKeyJson[json.pk_order] = newItemKey;
					} else {
						var newItem = itemJson[itemKey];
						newItem.nscannum = getAddScanedNum(newItem.nscannum, json.nscannum);
						newItem.nscanastnum = getAddScanedNum(newItem.nscanastnum, json.nscanastnum);
						itemJson[itemKey] = newItem;
					}
					if(NCMMPubUtil.isNotEmpty(hidAndNScanNum) && NCMMPubUtil.isNotEmpty(hidAndNScanNum[json.pk_order_b])) {
						var nScanedNum = getAddScanedNum(hidAndNScanNum[json.pk_order_b], json.nscannum);
						hidAndNScanNum[json.pk_order_b] = nScanedNum;
					} else {
						hidAndNScanNum[json.pk_order_b] = json.nscannum;
					}
				}
			}
		}
		if(needCommit == false) {
			$js.hideLoadingBar();
			$toast("没有选中任何记录！");
			return;
		}
		var checkResult = PoArriveUtil.checkWhenCommit(itemPKs, scanCount, scanNum);
		if(!NCMMPubUtil.isEmpty(checkResult)) {
			$js.hideLoadingBar();
			$alert(checkResult);
			return;
		}
		var billinfos = getBillInfos(headKey, headJson, itemKeyJson, itemJson);
		//测试连接
		NCMMDBUtil.testNCConnection(function(data) {
			if(data == false || data == "false") {
				$js.hideLoadingBar();
				$toast("连接服务器失败，无法提交！");
				return;
			}
			//$alert("billinfos=" + $jsonToString(billinfos));
			NCMMDBUtil.submitLocaldataToNC("21_23save", billinfos, function(commitInfo) {
				if(!NCMMPubUtil.isEmpty(commitInfo)) {
					if(commitInfo.return == null || commitInfo.return == "") {
						$js.hideLoadingBar();
						$alert("提交失败：" + $jsonToString(commitInfo));
					} else if(commitInfo["return"].returnFlag == 1) {
						var billbids = commitInfo.billbids;
						PoArriveUtil.deleteVOsAfterCommit(billbids);
						loadScanListData();
						$js.hideLoadingBar();
						$toast("提交成功！");
					} else {
						$js.hideLoadingBar();
						$alert("提交失败" + $jsonToString(commitInfo.return.returnDesc));
					}
				} else {
					$js.hideLoadingBar();
					$alert("提交失败");
				}
			});

		});

	}

	function getAddScanedNum(scanedNum, currentScanedNum) {
		if(scanedNum == null || scanedNum == "") {
			scanedNum += "00.00000";
		} else {
			scanedNum = parseFloat(scanedNum);
		}
		if(currentScanedNum == null || currentScanedNum == "") {
			currentScanedNum += "1.00000";
		} else {
			currentScanedNum = parseFloat(currentScanedNum);
		}
		var newScanedNum = parseFloat(scanedNum).add(parseFloat(currentScanedNum));
		return newScanedNum;
	}

	function convertVOtoBillInfo(scanPK) {
		for(var i = 0; i < scanPK.length; i++) {}
	}

	function getBillInfos(headKey, headJson, itemKeyJson, itemJson) {
		var billinfos = [];
		for(var i = 0; i < headKey.length; i++) {
			var head = headJson[headKey[i]];
			var itemkeys = itemKeyJson[headKey[i]];
			var items = getItems(itemkeys, itemJson, null);
			var billinfo = {
				"head": head,
				"items": items
			};
			billinfos.push({
				"billinfo": billinfo
			});
		}
		return billinfos;
	}

	function getItems(itemkeys, itemJson, bbitemJson) {
		var items = [];
		for(var i = 0; i < itemkeys.length; i++) {
			var item = itemJson[itemkeys[i]];
			if(!NCMMPubUtil.isEmpty(bbitemJson) && !NCMMPubUtil.isEmpty(bbitemJson[itemkeys[i]])) {
				//处理bbitem
				var bbitemArr = bbitemJson[itemkeys[i]];
				var bbitems = getBbitems(bbitemArr);
				item["bbitems"] = bbitems;
			}
			items.push({
				"item": item
			});
		}
		return items;
	}

	function com$yonyou$ncmm_pac_pda$PoArriveScanListController$showMenu(sender, args) {
		NCMMPubMenu.openDropDownList("btn_menu");
	}

	function com$yonyou$ncmm_pac_pda$PoArriveScanListController$search(sender, args) {
		NCMMPubUtil.quickFilter();
	}

	function com$yonyou$ncmm_pac_pda$PoArriveScanListController$onresume(sender, args) {
		loadScanListData();
	}
	var popDialogInfo = {
		"viewid": "panel_btn", //显示的控件的id，通常是一个容器控件div
		"popgravity": "popbottom", //popcenter|poptop|popbottom|popleft|popright,弹出后最终显示的位置
		// istouch : 'false'
	};

	function com$yonyou$ncmm_pac_pda$PoArriveScanListController$doEdit(sender, args) {
		$view.closePop(popDialogInfo);
		var row = $id("scanlistview").get("row");
		//row = $stringToJSON(row);
		$view.open({
			"viewid": "com.yonyou.ncmm_pac_pda.PoArriveScan", //目标页面（首字母大写）全名
			"isKeep": "true", //打开新页面的同时是否保留当前页面，true为保留，false为不保留
			"row": row
		});
	}

	function com$yonyou$ncmm_pac_pda$PoArriveScanListController$itemCancel(sender, args) {
		$view.closePop(popDialogInfo);
	}

	function com$yonyou$ncmm_pac_pda$PoArriveScanListController$close(sender, args) {
		$view.close();
	}

	function com$yonyou$ncmm_pac_pda$PoArriveScanListController$showItemButton(sender, args) {
		//$view.openPop(popDialogInfo);
		var row = {};
		row = $id("scanlistview").get("row");
		row = $stringToJSON(row);
		if(row && row["row"])
			return;
		$view.openPop(popDialogInfo);

	}
	com.yonyou.ncmm_pac_pda.PoArriveScanListController.prototype = {

		showDetail: com$yonyou$ncmm_pac_pda$PoArriveScanListController$showDetail,
		doEdit: com$yonyou$ncmm_pac_pda$PoArriveScanListController$doEdit,
		itemDelete: com$yonyou$ncmm_pac_pda$PoArriveScanListController$itemDelete,
		itemCancel: com$yonyou$ncmm_pac_pda$PoArriveScanListController$itemCancel,
		showItemButton: com$yonyou$ncmm_pac_pda$PoArriveScanListController$showItemButton,
		close: com$yonyou$ncmm_pac_pda$PoArriveScanListController$close,
		onresume: com$yonyou$ncmm_pac_pda$PoArriveScanListController$onresume,
		search: com$yonyou$ncmm_pac_pda$PoArriveScanListController$search,
		showMenu: com$yonyou$ncmm_pac_pda$PoArriveScanListController$showMenu,
		doCommit: com$yonyou$ncmm_pac_pda$PoArriveScanListController$doCommit,
		doChecked: com$yonyou$ncmm_pac_pda$PoArriveScanListController$doChecked,
		doAllChecked: com$yonyou$ncmm_pac_pda$PoArriveScanListController$doAllChecked,
		loadScanList: com$yonyou$ncmm_pac_pda$PoArriveScanListController$loadScanList,
		initialize: com$yonyou$ncmm_pac_pda$PoArriveScanListController$initialize,
		evaljs: com$yonyou$ncmm_pac_pda$PoArriveScanListController$evaljs
	};
	com.yonyou.ncmm_pac_pda.PoArriveScanListController.registerClass('com.yonyou.ncmm_pac_pda.PoArriveScanListController', UMP.UI.Mvc.Controller);
} catch(e) {
	$e(e);
}